package com.xiantm.study.thread.workthread.jdk;

import com.xiantm.study.thread.workthread.Request;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;

public class ClientThread extends Thread{
    private final ExecutorService channel;
    private int number = 0;
    private final Random random = new Random();
    public ClientThread(String name,ExecutorService channel) {
        super(name);
        this.channel = channel;
    }

    @Override
    public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + ": Started");
            while (true){
                Request request = new Request( threadName, number++);
                System.out.println(threadName +" requests " + request.getName()+"."+number);
                try {
                    channel.execute(request::execute);
                    sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }catch (RejectedExecutionException e){
                    System.out.println(threadName + ": " + e);
                    break;
                }
        }
    }
}
